<template>
    <div class="app-container">

        <div class="filter-container">
            <el-button class="filter-item" style="margin-left: 20px;" @click="goBack" type="primary" icon="arrow-left">返回课程列表</el-button>
            <el-button class="filter-item" style="margin-left: 20px;" @click="handleCreate" type="primary" icon="edit">新增音频</el-button>
            <el-button class="filter-item" style="margin-left: 20px;" @click="batchManager" type="primary" icon="edit">批量管理</el-button>
            <i style="padding-left: 50px;">课程名称： </i>
            <el-input style="width: 200px;" class="filter-item" v-model="courseName" disabled="disabled"></el-input>

            <el-select clearable style="width: 150px" class="filter-item" v-model="listQuery.orderKey" placeholder="排序" @change="handleFilter">
                <el-option v-for="item in orderKeyOptions" :key="item.key" :label="item.name" :value="item.key">
                </el-option>
            </el-select>
        </div>

        <el-table :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit highlight-current-row :row-class-name="tableRowClassName">

            <el-table-column align="center" label='音频ID' width="70">
                <template scope="scope">
                    {{scope.row.id}}
                </template>
            </el-table-column>
            <el-table-column label="排序" align="center" width="80">
                <template scope="scope">
                    <el-input v-show="scope.row.editing" size="small" v-model="scope.row.newSerial" @keyup.enter.native="commitUpdate(scope.row)" @keyup.esc.native="scope.row.editing=false"></el-input>
                    <span v-show="!scope.row.editing" @click="scope.row.editing=true" style="display: inline-block; width: 100%;">{{scope.row.serial}}</span>
                </template>
            </el-table-column>
            <el-table-column label="音频名称" align="center" >
                <template scope="scope">
                    {{scope.row.name}}
                </template>
            </el-table-column>
            <el-table-column label="试听状态" align="center" width="100">
                <template scope="scope">
                    {{scope.row.free === 1 ? "免费试听" : "非试听"}}
                </template>
            </el-table-column>
            <el-table-column label="上架状态" align="center" width="100">
                <template scope="scope">
                    {{scope.row.status === 1 ? "上架" : "下架"}}
                </template>
            </el-table-column>
            <el-table-column label="转码状态" align="center" width="100">
                <template scope="scope">
                    {{scope.row.transcodeStatus|parseTranscodeStatus}}
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" width="200">
                <template scope="scope">
                    <span>{{scope.row.createTime|parseTime}}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="300">
                <template scope="scope">
                    <el-button class="filter-item" size="small" type="primary" icon="edit" @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button v-if="scope.row.status === 1" size="small" type="danger" @click="toggle(scope.row, 0)">下架</el-button>
                    <el-button v-if="scope.row.status === 0" size="small" type="success" @click="toggle(scope.row, 1)">上架</el-button>
                    <el-button v-if="scope.row.free === 1" size="small" type="success" @click="toggleFree(scope.row, 0)">设为付费</el-button>
                    <el-button v-if="scope.row.free === 0" size="small" type="danger" @click="toggleFree(scope.row, 1)">设为免费</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
                           :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    import { getList, toggleStatus, toggleFree, updateSerial } from '@/api/audio';
    import { getDetail as getCourseDetail } from '@/api/course';
    import { getOrderKey } from '@/api/common';

    var defaultListQuery = {
        page: 1,
        pageSize: 30,
        searchCourseId: '',
        orderKey: 'AUDIO_SERIAL_ASC'
    }
    export default {
        data() {
            var listQuery = JSON.parse(JSON.stringify(defaultListQuery));
            var listQueryJson = sessionStorage.getItem(this.$route.path.replace(/\//g, '_'));
            if (listQueryJson) {
                listQuery = JSON.parse(listQueryJson);
            }
            return {
                list: null,
                total: null,
                courseName: '',
                orderKeyOptions: [],
                listQuery: listQuery,
                listLoading: true,
                selectedRowID: sessionStorage.getItem(this.$route.path.replace(/\//g, '_') + '_selected_row_id')
            }
        },
        created() {
            const reg = /\/(\d*)$/
            if (reg.test(this.$route.path)) {
                this.isUpdate = true;
                const ID = RegExp.$1;
                this.listQuery.searchCourseId = ID;
                defaultListQuery.searchCourseId = ID;
                this.getCourseInfo(ID);
            }
            this.getList();
            this.getOrderKeyList();
        },
        methods: {
            resetQuery() {
                this.listQuery = JSON.parse(JSON.stringify(defaultListQuery));
                this.selectedRowID = '';
                sessionStorage.removeItem(this.$route.path.replace(/\//g, '_') + '_selected_row_id')
                this.getList();
            },
            tableRowClassName(row) {
                if (this.selectedRowID && row.id == this.selectedRowID) {
                    return 'sstt-selected-row';
                }
            },
            getList() {
                this.listLoading = true;
                getList(this.listQuery).then(response => {
                    this.list = response.data.data.map(v => {
                        v.editing = false;
                        v.newSerial = v.serial;
                        return v;
                    });
                    this.total = response.data.totalCount;
                    this.listLoading = false;
                    sessionStorage.setItem(this.$route.path.replace(/\//g, '_'), JSON.stringify(this.listQuery));
                }).catch(err => {
                    console.log(err);
                    this.listLoading = false;
                });
            },
            getCourseInfo(courseID) {
                getCourseDetail(courseID).then(response => {
                    this.courseName = response.data.name;
                }).catch(err => {
                    console.log(err)
                });
            },
            getOrderKeyList() {
                getOrderKey('admin_audio').then(response => {
                    this.orderKeyOptions = this.orderKeyOptions.concat(response.data);
                }).catch(err => {
                    console.log(err)
                });
            },
            commitUpdate(item) {
                item.editing = false;
                if (isNaN(item.newSerial) || item.newSerial <= 0) {
                    item.newSerial = item.serial;
                    return;
                }
                if (item.newSerial !== item.serial) {
                    updateSerial(item.courseId, item.id, item.newSerial).then(() => {
                        this.$notify({
                            title: '成功',
                            message: '更新成功',
                            type: 'success',
                            duration: 2000
                        });
                        item.serial = item.newSerial;
                    }).catch(err => {
                        console.log(err)
                        this.$message({
                            title: '失败',
                            message: '原因:' + err.msg,
                            type: 'error',
                            duration: 2000
                        });
                        item.newSerial = item.serial;
                    });
                }
            },
            handleFilter() {
                this.getList();
            },
            handleCreate() {
                this.$router.push('/course/audio/add/' + this.listQuery.searchCourseId);
            },
            batchManager() {
                this.$router.push('/course/audio/batch/' + this.listQuery.searchCourseId);
            },
            handleEdit(id) {
                sessionStorage.setItem(this.$route.path.replace(/\//g, '_') + '_selected_row_id', id)
                this.$router.push('/course/audio/update/' + id);
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.page = val;
                this.getList();
            },
            toggle(item, status) {
                toggleStatus(item.id, status).then(() => {
                    this.$notify({
                        title: '成功',
                        message: '更新状态成功',
                        type: 'success',
                        duration: 2000
                    });
                    item.status = status;
                }).catch(err => {
                    console.log(err)
                });
            },
            toggleFree(item, free) {
                toggleFree(item.id, free).then(() => {
                    this.$notify({
                        title: '成功',
                        message: '更新试听状态成功',
                        type: 'success',
                        duration: 2000
                    });
                    item.free = free;
                }).catch(err => {
                    console.log(err)
                });
            },
            goBack() {
                this.$router.go(-1);
            },
            checkParamError() {
                if (this.listQuery.searchId && !/^\d*$/.test(this.listQuery.searchId)) {
                    return '课程ID必须是数字';
                }
                return '';
            }
        }
    };
</script>